<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Service\User;

use App\Models\SignRecord;
use App\Models\SignRule;
use App\Models\User;
use App\Service\BaseService;

class SignService extends BaseService
{
    public function sign(User $user)
    {
        // 检查今天是否已签到
        if ($this->hasSignedToday($user)) {
            return ['success' => false, 'message' => '您今天已经签到过了'];
        }
        // 计算连续签到天数
        $continuousDays = $this->calculateContinuousDays($user);
        if ($continuousDays == 0) {
            return ['success' => false, 'message' => '您已达到签到次数上线'];
        }
        //签到记录
        $reward_points = $this->giveBaseReward($user);
        if ($reward_points) {
            return [
                'success' => true,
                'reward_points' => $reward_points,
            ];
        }
        return ['success' => false, 'message' => '服务器忙,签到失败'];
    }

    // 检查今天是否已签到
    private function hasSignedToday(User $user): bool
    {
        return $user->signRecords()
            ->whereDate('sign_date', now()->toDateString())
            ->exists();
    }

    // 获取昨天签到
    private function signedYesterday(User $user)
    {
        return $user->signRecords()
            ->whereDate('sign_date', now()->subDay()->toDateString())
            ->first();
    }

    // 计算签到天数
    private function calculateContinuousDays(User $user): int
    {
        $rule = $this->getRule();
        $signDays = $user->signRecords()->count();
        if ($rule->days == $signDays) {
            return 0;
        }
        return 1;
    }

    // 发放记录
    private function giveBaseReward(User $user)
    {
        $rule = $this->getRule();
        $reward_points = $rule->reward_points ?? 10; // 每日基础积分
        $yesterday = $this->signedYesterday($user);
        $continuous_days = 0;
        if ($yesterday) {
            $continuous_days = $yesterday->continuous_days ?? 0 + $continuous_days;
        }
        $model = SignRecord::query()->create([
            'user_id' => $user->id,
            'sign_rule_id' => $rule->id,
            'reward_points' => $reward_points,
            'continuous_days' => $continuous_days,
            'sign_date' => now(),
        ]);
        if ($model) {
            PointAccountServices::make()->recharge($user->id, $reward_points, '签到赠送积分:' . $reward_points);
            return $reward_points;
        }
        return 0;
    }

    private function getRule()
    {
        return SignRule::query()->latest()->first();
    }
}
